from django.db import transaction
from rest_framework import serializers
from goods.models import SKU, Goods, SpecificationOption, GoodsSpecification, SKUSpecification

class SKUSpecificationSerialzier(serializers.ModelSerializer):
    """
        SKU规格表序列化器
    """
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()
    class Meta:
        model = SKUSpecification  # SKUSpecification中sku外键关联了SKU表
        fields = ("spec_id", 'option_id')



# SKU表数据
class SKUSerializer(serializers.ModelSerializer):
    # 添加2个字段来接收 category_id 和 spu_id
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    # 自己定义spu和category字段为 StringRelatedField
    spu = serializers.StringRelatedField(read_only=True)
    category = serializers.StringRelatedField(read_only=True)
    # 定义specs字段来接收规格信息
    # 规格信息是一个列表 many=Tue
    # 规格信息 spec_id 和 option_id 和 SKUSpecification 对应
    # 于是我们定义 SKUSpecificationSerialzier
    # 期望 SKUSpecificationSerialzier 序列化器帮助我们实现 反序列化操作
    specs = SKUSpecificationSerialzier(many=True)
    class Meta:
        model=SKU
        fields='__all__'

    # 更新SKU表数据
    def update(self, instance, validated_data):
        # 获取规格信息,并从validated_data数据中,删除规格信息数据
        specs_data = validated_data.pop('specs')

        # 方案一： 调用父类 ，去实现没有问题的数据更新
        super().update(instance, validated_data)

        # 方案二
        # 获取pk
        # pk = self.context['view'].kwargs.get('pk')
        # #更新数据
        # SKU.objects.filter(id=pk).update(**validated_data)

        # 方案三 把父类的源码 拿来
        # for attr, value in validated_data.items():
        #     setattr(instance, attr, value)
        # instance.save()

        # 对规格信息进行遍历,来保存商品规格信息
        for spec_data in specs_data:
            # item {spec_id: "4", option_id: 8}
            SKUSpecification.objects.filter(sku=instance,
                                            spec_id=spec_data.get('spec_id')). \
                update(option_id=spec_data.get('option_id'))

        return instance
    # 获取SKU表数据
    def create(self, validated_data):
        # 获取规格信息,并从validated_data数据中,删除规格信息数据
        specs_data = validated_data.pop('specs')

        with transaction.atomic():
            # 开启事务
            savepoint = transaction.savepoint()
            # 保存sku
            sku = SKU.objects.create(**validated_data)
            # 对规格信息进行遍历,来保存商品规格信息
            for spec_data in specs_data:
                SKUSpecification.objects.create(sku=sku, **spec_data)
            # 清除保存点
            transaction.savepoint_commit(savepoint)
            # 返回sku
            return sku


from rest_framework import serializers
from goods.models import GoodsCategory
# 获取三级分类信息
class SKUCategorieSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategory
        fields = "__all__"



# 获取SPU表名称数据
class GoodsSimpleSerializer(serializers.ModelSerializer):
    class Meta:
        model=Goods
        fields='__all__'



# 获取SPU商品规格信息
class GoodsOptineSerializer(serializers.ModelSerializer):
    class Meta:
        model = SpecificationOption
        fields=('id','value')

class GoodsSpecSerialzier(serializers.ModelSerializer):

    goods = serializers.StringRelatedField(read_only=True)
    goods_id = serializers.IntegerField(read_only=True)
    # 关联序列化返回 规格选项信息
    options = GoodsOptineSerializer(read_only=True,many=True) # 使用规格选项序列化器

    class Meta:
        model = GoodsSpecification # SPUSpecification中的外键spu关联了SPU商品表
        fields="__all__"


